﻿using System;
using System.ServiceModel;

namespace WCFLib
{
    public class ProxyHelper<T>
    {
        public ProxyHelper(string baseAddress)
        {
            var tcpBinding = new NetTcpBinding(SecurityMode.None);
            var endPoint = new EndpointAddress(new Uri(new Uri(baseAddress), typeof(T).Name));
            _factory = new ChannelFactory<T>(tcpBinding, endPoint);
        }

        private readonly ChannelFactory<T> _factory;

        private T CreateChannel()
        {
            return _factory.CreateChannel();
        }

        public void Run(Action<T> action)
        {
            var proxy = CreateChannel();
            action(proxy);
            ((ICommunicationObject)proxy).Close();
        }

        public TResult Run<TResult>(Func<T, TResult> func)
        {
            var proxy = CreateChannel();
            var result = func(proxy);
            ((ICommunicationObject)proxy).Close();

            return result;
        }
    }
}
